package com.sxit.tdf.server.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.sxit.tdf.server.entity.File;
import com.sxit.tdf.server.entity.FileApprove;
import com.sxit.tdf.server.entity.User;
import com.sxit.tdf.server.entity.bo.FileApproveInfoBo;
import com.sxit.tdf.server.entity.vo.FailApprovalFileVo;
import com.sxit.tdf.server.entity.vo.InsertApproveFileVo;
import com.sxit.tdf.server.entity.vo.PassApprovalFileVo;
import com.sxit.tdf.server.exception.TdfException;
import com.sxit.tdf.server.response.R;
import com.sxit.tdf.server.service.IFileApproveService;
import com.sxit.tdf.server.service.IFileService;
import com.sxit.tdf.server.service.IUserService;
import com.sxit.tdf.server.util.EmailSendUtil;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 前端控制器
 *
 * @author 橙子高
 * @since 2022-03-19
 */
@RestController
@RequestMapping("/file-approve")
public class FileApproveController {

  @Autowired IFileApproveService fileApproveService;
  @Autowired IUserService userService;
  @Autowired IFileService fileService;
  @Autowired EmailSendUtil emailSendUtil;

  @Operation(summary = "上传审批文件")
  @PostMapping("upLoadApproveFile")
  @Transactional
  public R upLoadApproveFile(
      @Valid InsertApproveFileVo insertApproveFileVo, @RequestParam("file") MultipartFile file) {

    try {
      Boolean flag = fileApproveService.upLoadApproveFile(insertApproveFileVo, file);

      if (flag) {
        return R.ok("添加成功");
      } else {
        return R.error("添加失败");
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new TdfException("上传失败");
    }
  }

  @Operation(summary = "获取个人审批文件信息")
  @GetMapping("/getPrivateApproveFileList")
  public R getPrivateApproveFileList() {
    List<FileApproveInfoBo> list = fileApproveService.getPrivateApproveFileList();
    return R.ok().put("data", list);
  }

  @Operation(summary = "取消文件上传")
  @GetMapping("/cancelFileApprove")
  @Transactional
  public R cancelFileApprove(@RequestParam("fileId") String fileId) {

    fileApproveService.cancelFileApprove(fileId, StpUtil.getLoginIdAsString());

    return R.ok("取消成功");
  }

  @Operation(summary = "获得系部所有人的审批文件")
  @GetMapping("/getDeptApproverList")
  public R getDeptApproverList(@RequestParam("deptId") Integer deptId) {

    String userId = StpUtil.getLoginIdAsString();

    User byId = userService.getById(userId);

    if (!Objects.equals(byId.getDeptId(), deptId)
        && byId.getRoleId() != 1
        && byId.getRoleId() != 2) {
      throw new TdfException("请勿越权审批");
    }

    List<FileApproveInfoBo> list = fileApproveService.getDeptApproverList(deptId);

    return R.ok().put("data", list);
  }

  @Operation(summary = "审批通过")
  @PostMapping("passApprovalFile")
  @Transactional
  public R passApprovalFile(@Valid @RequestBody PassApprovalFileVo passApprovalFileVo) {

    // 是否具有系部审批权力
    boolean isDeptApproval = StpUtil.hasPermission("DEPT:APPROVAL");
    // 是否具有全部文件的审批权限
    boolean isApproval = StpUtil.hasPermission("DOCUMENT_APPROVAL:APPROVAL");
    if (!isApproval) {
      if (!isDeptApproval) {
        throw new TdfException("无此权限");
      } else {
        // 判断系部是否先等不允许跨系部审批

        // 获取审批用户的信息
        User userInfo = userService.getById(StpUtil.getLoginIdAsString());

        // 获取被审批用户的信息
        FileApprove byId1 = fileApproveService.getById(passApprovalFileVo.getFileId());
        User user = userService.getById(byId1.getFileOwner());

        // 比对
        if (!Objects.equals(userInfo.getDeptId(), user.getDeptId())) {
          throw new TdfException("请勿审批其他系部文件");
        }
      }
    }

    FileApprove fileApprove = new FileApprove();

    fileApprove.setFileState(2);
    fileApprove.setId(passApprovalFileVo.getFileId());
    fileApprove.setFileApprover(StpUtil.getLoginIdAsString());
    fileApprove.setFileCause("审核通过");

    fileApprove.setUpdateTime(LocalDateTime.now());
    fileApprove.setFinalTime(LocalDateTime.now());

    boolean update = fileApproveService.updateById(fileApprove);

    FileApprove byId = fileApproveService.getById(passApprovalFileVo.getFileId());

    File file = new File();
    file.setId(byId.getFileId());
    file.setFileType("1");
    fileService.updateById(file);

    if (update) {
      FileApprove byId1 = fileApproveService.getById(passApprovalFileVo.getFileId());
      User user = userService.getById(byId1.getFileOwner());
      emailSendUtil.SendMsg("你好，您上传审批的文件已经审批成功，请即使查阅~", user.getEmail(), "审批成功");

      return R.ok("通过");
    } else {
      R.error("失败");
    }

    return R.ok();
  }

  @Operation(summary = "审批未通过")
  @PostMapping("failApprovalFile")
  public R failApprovalFile(@Valid @RequestBody FailApprovalFileVo failApprovalFileVo) {

    // 是否具有系部审批权力
    boolean isDeptApproval = StpUtil.hasPermission("DEPT:APPROVAL");
    // 是否具有全部文件的审批权限
    boolean isApproval = StpUtil.hasPermission("DOCUMENT_APPROVAL:APPROVAL");
    if (!isApproval) {
      if (!isDeptApproval) {
        throw new TdfException("无此权限");
      } else {
        // 判断系部是否先等不允许跨系部审批

        // 获取审批用户的信息
        User userInfo = userService.getById(StpUtil.getLoginIdAsString());

        // 获取被审批用户的信息
        FileApprove byId1 = fileApproveService.getById(failApprovalFileVo.getFileId());
        User user = userService.getById(byId1.getFileOwner());

        // 比对
        if (!Objects.equals(userInfo.getDeptId(), user.getDeptId())) {
          throw new TdfException("请勿审批其他系部文件");
        }
      }
    }

    FileApprove fileApprove = new FileApprove();

    fileApprove.setFileState(3);
    fileApprove.setId(failApprovalFileVo.getFileId());
    fileApprove.setFileApprover(StpUtil.getLoginIdAsString());
    fileApprove.setFileCause(failApprovalFileVo.getCause());

    fileApprove.setUpdateTime(LocalDateTime.now());

    boolean update = fileApproveService.updateById(fileApprove);
    if (update) {
      FileApprove byId1 = fileApproveService.getById(failApprovalFileVo.getFileId());
      User user = userService.getById(byId1.getFileOwner());
      emailSendUtil.SendMsg("你好，您上传审批的文件已经审批失败，请即使查阅~", user.getEmail(), "审批失败");

      return R.ok("通过");
    } else {
      R.error("失败");
    }

    return R.ok();
  }

  @Operation(summary = "重新上传审批文件")
  @PostMapping("reUpLoadApproveFile")
  @Transactional
  public R reUpLoadApproveFile(
      @Valid InsertApproveFileVo insertApproveFileVo, @RequestParam("file") MultipartFile file) {

    try {
      // 逻辑删除之前的文件
      fileService.deleteById(insertApproveFileVo.getFileId());
      // 插入新的文件
      Boolean flag = fileApproveService.reUpLoadApproveFile(insertApproveFileVo, file);

      if (flag) {
        return R.ok("添加成功");
      } else {
        return R.error("添加失败");
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new TdfException("上传失败");
    }
  }
}
